//
//  RCVideoCatManager.m
//  SanYiTeaching
//
//  Created by ChenHao on 2019/9/6.
//  Copyright © 2019 SanYi. All rights reserved.
//

#import "RCVideoCatManager.h"
#import "SYSendVideoViewController.h"
@interface RCVideoCatManager()<TZImagePickerControllerDelegate>

@end
@implementation RCVideoCatManager
- (instancetype)init{
    if (self = [super init]) {
    }
    return self;
}

+ (RCVideoCatManager *)shareManager{
    static RCVideoCatManager* manager = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        manager = [[[self class] alloc] init];
    });
    return manager;
}
-(void)openChooseVideoControllerExportVideo{
    SYSendVideoViewController *imagePickerVc = [[SYSendVideoViewController alloc]init];
    imagePickerVc.maxImagesCount = 1 ;
    imagePickerVc.pickerDelegate = self;
    
    imagePickerVc.view.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    //展示相册中的视频
    imagePickerVc.allowPickingVideo = YES;
    //不展示图片
    imagePickerVc.allowPickingImage = NO;
    //不显示原图选项
    imagePickerVc.allowPickingOriginalPhoto = NO;
    //按时间排序
    imagePickerVc.sortAscendingByModificationDate = YES;
    // 是否自动dismiss

    imagePickerVc.autoDismiss = NO;

    
    // 点击取消n按钮
    __weak typeof(self) weakSelf = self;
    imagePickerVc.cancelBtnClickAndBanck = ^{
//        [weakSelf.window makeKeyAndVisible];
        //    注意: 千万不要直接调用 resignKeyWindow(Apple文档上有说明), 在其他窗口执行 makeKeyAndVisible 的时候, 当前窗口会自动执行 resignKeyWindow, 然后被自动释放
        
        // 2.移除subWin的根控制器
        weakSelf.window.rootViewController = nil;
        
        // 3.将subWin置空
        weakSelf.window = nil;
    };
    
    
    self.window = [[UIWindow alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    
    
    
    // 2.添加窗口根控制器
    self.window.rootViewController = imagePickerVc;
    
    // 3.设置显示在当前视图上
//    [self.window makeKeyAndVisible];
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(PHAsset *)asset{
    
    //iOS8以后返回PHAsset
    PHAsset *phAsset = asset;
    
    if (phAsset.mediaType == PHAssetMediaTypeVideo) {
        //从PHAsset获取相册中视频的url
        __weak typeof(self) weakSelf = self;

        PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
        options.version = PHImageRequestOptionsVersionCurrent;
        options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
        PHImageManager *manager = [PHImageManager defaultManager];
        [manager requestAVAssetForVideo:phAsset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            AVURLAsset *urlAsset = (AVURLAsset *)asset;
            
            NSURL *url = urlAsset.URL;
            NSUInteger second = 0;
            second = urlAsset.duration.value / urlAsset.duration.timescale;
            //                self.videoUrl = url;
            NSLog(@"%@",url);
            
            if (self.chooseVideoBlock) {
                self.chooseVideoBlock(url,coverImage,second);
            }
            
//            [weakSelf.window makeKeyAndVisible];
            //    注意: 千万不要直接调用 resignKeyWindow(Apple文档上有说明), 在其他窗口执行 makeKeyAndVisible 的时候, 当前窗口会自动执行 resignKeyWindow, 然后被自动释放
            
            // 2.移除subWin的根控制器
            weakSelf.window.rootViewController = nil;
            
            // 3.将subWin置空
            weakSelf.window = nil;
        }];
    }

}
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingGifImage:(UIImage *)animatedImage sourceAssets:(PHAsset *)asset{
    
}

//视频裁剪
- (void)cropWithVideoUrlStr:(NSURL *)videoUrl start:(CGFloat)startTime end:(CGFloat)endTime completion:(void (^)(NSURL *outputURL, Float64 videoDuration, BOOL isSuccess))completionHandle
{
    AVURLAsset *asset =[[AVURLAsset alloc] initWithURL:videoUrl options:nil];
    
    //获取视频总时长
    Float64 duration = CMTimeGetSeconds(asset.duration);
    
    NSString *outputPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"dafei.mp4"];
    NSURL *outputURL = [NSURL fileURLWithPath:outputPath];
    
    //如果文件已经存在，先移除，否则会报无法存储的错误
    NSFileManager *manager = [NSFileManager defaultManager];
    [manager removeItemAtPath:outputPath error:nil];
    
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:asset];
    if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality])
    {
        
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]
                                               initWithAsset:asset presetName:AVAssetExportPresetPassthrough];
        
        exportSession.outputURL =  outputURL;
        //视频文件的类型
        exportSession.outputFileType = AVFileTypeQuickTimeMovie;
        //输出文件是否网络优化
        exportSession.shouldOptimizeForNetworkUse = YES;
        
        //要截取的开始时间
        CMTime start = CMTimeMakeWithSeconds(startTime, asset.duration.timescale);
        //要截取的总时长
        CMTime duration = CMTimeMakeWithSeconds(endTime - startTime,asset.duration.timescale);
        CMTimeRange range = CMTimeRangeMake(start, duration);
        exportSession.timeRange = range;
        
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status]) {
                case AVAssetExportSessionStatusFailed:
                {
                    NSLog(@"合成失败：%@", [[exportSession error] description]);
                    completionHandle(outputURL, endTime, NO);
                }
                    break;
                case AVAssetExportSessionStatusCancelled:
                {
                    completionHandle(outputURL, endTime, NO);
                }
                    break;
                case AVAssetExportSessionStatusCompleted:
                {
                    //成功
                    completionHandle(outputURL, endTime, YES);
                    
                }
                    break;
                default:
                {
                    completionHandle(outputURL, endTime, NO);
                } break;
            }
        }];
    }
}
@end
